"""
Created on 23-Jul-2009

@author: dexen
"""
import threading


import os
import sys
import time
import logging

import multiprocessing as mp

import rpyc
from rpyc.utils import server

import dexen
from dexen.system import node
from dexen.system.base import service, MyManager
from dexen.system.node.master import scheduler, comm

MyManager.register("MasterComm", comm.MasterComm)
   
#===============================================================================
# Helper
#===============================================================================
def start(mastername, _nodename):
    global conn, masterdir, manager, nodename
    
    nodename = _nodename
    manager = MyManager()
    manager.start()
     
    logging.basicConfig(level=logging.DEBUG)

    masterdir = os.path.join(node.TEMP_DIR, mastername)
    if not os.path.exists(masterdir):
        os.mkdir(masterdir)
    
    logging.debug("My pid is %d", os.getpid())
    
    MasterService.ALIASES = [mastername]
    svr = server.ThreadedServer(MasterService, port=3333, 
                                protocol_config=service.default_config)
    svr.start()


#===============================================================================
# Service
#===============================================================================
class MasterService(dexen.Service):
    def on_connect(self):
        logging.info("node_manager is connected")
    
    def on_disconnect(self):
        pass
        
    def add_slaves(self, slave_names):
        self.comm.add_slaves(slave_names)

    def run_schema(self, spec):
        self.spec = rpyc.classic.obtain(spec)
        self.spec.masterdir = masterdir
        #self.schema_zip = schema_zip TODO: type buffer --> netref !
        print "master->run_schema(), the type, len", type(self.spec.schema_zip),\
                                                     len(self.spec.schema_zip)  
        self.comm = manager.MasterComm()
        self.sp = mp.Process(target=scheduler.run, args=(self.spec, self.comm))
        #self.sp = mp.Process(target=scheduler.test_run, args=(self.spec,))
        self.sp.name = "Scheduler"
        self.sp.start()
        print "Master is running"

    def get_info(self):
        return self.comm.get_info()
    
